package top.h1234.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // request强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 登录、注册相关的资源
        String[] urls = {"/login.jsp", "/imgs/", "/css/", "/loginServlet", "/register.jsp", "/registerServlet", "checkCodeServlet"};

        // 获取用户请求的资源
        String url = request.getRequestURL().toString();

        // 判断用户请求的资源是否为登录、注册相关的资源中的任何一个
        for (String u : urls) {
            if (url.contains(u)) {
                // 放行
                filterChain.doFilter(request, servletResponse);
                return;
            }
        }

        // 用户请求的资源为其他资源，则需判断是否已经登录

        // 获取session
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        // 判断session是否存在
        if (user != null) {
            // 已经登录，可以访问
            // 放行
            filterChain.doFilter(request, servletResponse);
        } else {
            // 没有登录，跳转到登录页
            request.setAttribute("login_msg", "请先进行登录！");
            request.getRequestDispatcher("/login.jsp").forward(request, servletResponse);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
